package com.zed.api.common.param;

import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;

/**
 * 初始化参数配置项目构建器
 *
 * @author Zed
 */
public class ParamsBuilder {

    protected Map<String, Object> params;

    /**
     * 无参构造方法
     */
    public ParamsBuilder() {
        super();
    }

    /**
     * 无参构造方法
     */
    public ParamsBuilder(int initialCapacity) {
        this.params = new HashMap<>(initialCapacity);
    }

    /**
     * 无参构造方法
     */
    public ParamsBuilder(Map<String, Object> params) {
        this.params = params;
    }

    /**
     * 获取一组参数
     *
     * @return {@link Map}
     */
    public Map<String, Object> getParams() {
        return this.params;
    }

    /**
     * 获取参数
     *
     * @param name {@link String}
     * @return {@link Object}
     */
    public Object getParameter(String name) {
        if (this.params != null) {
            return this.params.get(name);
        }
        return null;
    }


    /**
     * 设置参数
     * <p>
     * 不支持覆写已存在参数.
     *
     * @param name  {@link String},参数名
     * @param value {@link Object},参数值
     * @return {@link ParamsBuilder}
     */
    public ParamsBuilder setParameter(String name, Object value) {
        return this.setParameter(name, value, null);
    }

    /**
     * 设置参数
     * <p>
     * 不支持覆写已存在参数.
     *
     * @param name   {@link String},参数名
     * @param value  {@link Object},参数值
     * @param action {@link Consumer},参数设置是否成功的回调函数,可以为null.
     * @return {@link ParamsBuilder}
     */
    public ParamsBuilder setParameter(String name, Object value, Consumer<Boolean> action) {
        if (name != null && value != null) {
            if (this.params == null) {
                this.params = new HashMap<>();
            }
            boolean success = this.params.putIfAbsent(name, value) == null;
            if (action != null) {
                action.accept(success);
            }
        }

        return this;
    }

}
